<template>
  <div id="DetailEnvInfo" class="detail-env-info">
    <div class="header">
      <span>组件环境信息</span>
      <el-checkbox
        v-model="isSelectAll"
        style="padding: 10px"
        size="mini"
        :disabled="buildStep[componentId] === 1"
        :indeterminate="isIndeterminate"
        @change="selectAll"
      >全选</el-checkbox>
    </div>
    <div class="tags-wrapper">
      <el-row :gutter="20">
        <el-checkbox-group v-model="selectedEnvIds" @change="handleChange">
          <el-col
            v-for="env in localEnvList"
            :key="env.id"
            :span="6"
            class="card-col"
          >
            <el-tooltip
              effect="dark"
              class="tip-item"
              :content="getBadgeValue(env, projectStatus)['tip']"
              placement="right-start"
            >
              <el-badge
                :value="getBadgeValue(env, projectStatus)['txt']"
                type="info"
                class="item"
              >
                <el-checkbox
                  :label="env.id"
                  border
                  :disabled="buildStep[componentId] === 1"
                >
                  {{ env.host }}
                </el-checkbox>
              </el-badge>
            </el-tooltip>
          </el-col>
        </el-checkbox-group>
      </el-row>
    </div>
    <div class="operation-btns">
      <div style="display: flex;justify-content: center;align-items: center; margin-top: 10px;">
        <el-button
          size="mini"
          type="primary"
          :disabled="buildStep[componentId] === 1 || selectedEnvIds.length === 0"
          @click="doBuildOp"
        >构建</el-button>
        <el-button size="mini" @click="cancelSet">取消</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { envNetStatus } from '@/utils/utils'
import { getComponentEnvList } from '@/api/component'

export default {
  name: 'DetailEnvInfo',
  props: {
    componentId: {
      type: String,
      required: true,
      default: ''
    }
  },
  emits: ['detail-config-cancel', 'detail-config-build'],
  data() {
    return {
      // 待升级环境ID
      selectedEnvIds: [],
      localEnvList: [],
      isSelectAll: false,
      isIndeterminate: false
    }
  },
  computed: {
    ...mapGetters([
      'projectStatus',
      'buildStep',
      'detailConfigs'
    ])
  },
  mounted() {
    this.initCompEnvList()
  },
  methods: {
    // 获取组件所在环境信息
    initCompEnvList() {
      getComponentEnvList({ componentId: this.componentId }).then(res => {
        const list = res.data
        if (list && list.length > 0) {
          list.forEach(item => {
            this.localEnvList.push(item)
            // 默认选中所有环境
            this.selectedEnvIds.push(item.id)
          })

          const cfg = this.detailConfigs[this.componentId]
          if (!cfg) {
            this.isSelectAll = true
          } else {
            this.selectedEnvIds = []
            const upgradeEnvIds = cfg['upgradeEnvIds']
            if (upgradeEnvIds && upgradeEnvIds.length > 0) {
              upgradeEnvIds.forEach(item => this.selectedEnvIds.push(item))
            }
          }
        }
      }).catch(err => {
        console.error(err)
        this.$message.error('获取组件环境信息失败！！')
      })
    },

    getBadgeValue(env, stateProjectStatus) {
      return envNetStatus(env.projectId, env.id, stateProjectStatus) ? { txt: '☀️', tip: '网络通畅' }
        : { txt: '⛈️', tip: '网络异常' }
    },

    doBuildOp() {
      this.saveCfg()
      this.$emit('detail-config-build')
    },

    // 保存配置信息，在切换tab页时由父组件调用
    saveCfg() {
      this.$store.commit('project/SET_DETAIL_CONFIG', {
        componentId: this.componentId,
        upgradeEnvIds: this.selectedEnvIds
      })
    },

    cancelSet() {
      this.$emit('detail-config-cancel')
    },
    selectAll(val) {
      this.isSelectAll = val
      if (this.isSelectAll) {
        this.selectedEnvIds = []
        this.localEnvList.forEach(item => {
          this.selectedEnvIds.push(item.id)
        })
      } else {
        this.selectedEnvIds = []
      }
    },
    handleChange(value) {
      const checkedCount = value.length
      this.isSelectAll = checkedCount === this.localEnvList.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.localEnvList.length
    }
  }
}
</script>
<style scoped>
.card-col {
  margin-bottom: 20px;
}

.detail-env-info {
  width: 100%;
  height: 500px;
  text-align: center;
  position: relative;
  padding: 4px;
  box-sizing: border-box;
}

.detail-env-info .header span {
  font-weight: 700;
  font-size: 16px;
}

.tags-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 标签间距 */
  align-items: center;
  justify-content: center;
  max-height: 400px; /* 最大高度限制 */
  overflow-y: auto; /* 超出滚动 */
  border: 0;
  margin-top: 20px;
}
.tags-wrapper ::v-deep .el-row {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}

.tip-item {
  margin: 4px;
}

.operation-btns {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px;
  z-index: 2000;
}

::v-deep .el-badge__content--info{
  background-color: transparent !important;
}
::v-deep .el-badge__content{
  font-size: 18px !important;
}
::v-deep .el-badge__content.is-fixed {
  right: 20px !important;
}
</style>
